<template>
  <el-card class="box-card">
    <el-form ref="formRef" :model="settingForm" label-position="right" label-width="120">
      <el-form-item label="logo" prop="logo" :rules="[{required: true, message:'请选择', trigger:'change'}]">
        <el-upload
          class="avatar-uploader"
          drag
          ref="avatarUploadRef"
          accept="png,jpg,jpeg"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="onChangeImg"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-row>
        <el-col :span="24">
          <el-form-item label="单位名称" prop="unit_name" :rules="[{required: true, message:'请输入', trigger:'blur'}]">
            <el-input v-model="settingForm.unit_name"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="系统名称" prop="system_name" :rules="[{required: true, message:'请输入', trigger:'blur'}]">
            <el-input v-model="settingForm.system_name"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="播放端IP" prop="ip_addr" :rules="[{required: true, message:'请输入', trigger:'blur'},{required: true, validator: ipValidator, trigger: 'blur'}]">
            <el-input v-model="settingForm.ip_addr"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="播放端端口" prop="port" :rules="[{required: true, message:'请输入', trigger:'blur'},{required: true, validator: validatePort, trigger: 'blur'} ]">
            <el-input-number v-model="settingForm.port"></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-button type="primary" @click="onSubmit(formRef)">保存</el-button>
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { FormOption, FormOptionList } from '@/types/form-option';
import { CirclePlusFilled } from '@element-plus/icons-vue';
import  siteConfigService  from '@/api/service/siteConfigService'
import { uploadFile,getFileStream} from '@/api/index'
import type { FormInstance, UploadProps, UploadFile } from 'element-plus';
import type { SiteConfig } from '@/types/siteConfig';
import { useSystemStore } from '@/store/system';

const formRef = ref<FormInstance>()
const avatarUploadRef = ref()
const imageUrl = ref('')
const uploadedFile = ref<File | null>(null)

let settingForm = ref<SiteConfig>({
  id: 1,
  logo: '',
  unit_name: '',
  system_name: '',
  ip_addr: '',
  port: 0,
})

const system = useSystemStore()
// 加载数据
const getData = async () => {
  try {
    const res = await siteConfigService.getById(1)
    if (res && Object.keys(res).length > 0) {
      settingForm.value = res;
      //console.log('settingForm==', settingForm.value)
    //  localStorage.setItem('systemName',settingForm.value.system_name)
      system.setSystemName(settingForm.value.system_name)
      system.setUnit_name(settingForm.value.unit_name)
      // 如果logo字段有值，加载图片
      if (settingForm.value.logo) {
        try {
          const file = await getFileStream(settingForm.value.logo);
          imageUrl.value = URL.createObjectURL(new Blob([file.buffer]))
          system.setSystemIcon(imageUrl.value)
        } catch (error) {
          console.warn('无法加载logo图片:', error);
        }
      }
    }
  } catch (error) {
    console.error('加载配置数据失败:', error);
  }
}

onMounted(() => {
  getData();
});

// 提交
const onSubmit = async (formEl: FormInstance | undefined) => {
  
  if (!formEl) return;
  
  formEl.validate(async (valid) => {
    if (!valid) return;
    
    try {
      // 更新配置
      const result = await siteConfigService.update(settingForm.value)
      ElMessage.success('提交成功！');
      getData();
    } catch (error) {
      console.error('保存失败:', error);
      ElMessage.error('保存失败，请重试');
    }
  });
};

const onChangeImg = async (file: UploadFile) => {
  if (!file.raw) return;
  // 创建本地预览
  imageUrl.value = URL.createObjectURL(file.raw)
  // 保存文件对象，提交时再上传
  uploadedFile.value = file.raw
   // 如果有新上传的文件，先上传文件
  if (uploadedFile.value) {
    try {
      const fileName = await uploadFile(uploadedFile.value);
      settingForm.value.logo = fileName;
      uploadedFile.value = null;
    } catch (error) {
      console.error('文件上传失败:', error);
      ElMessage.error('文件上传失败，请重试');
    }
  }
};

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2MB!')
    return false
  }
  return true
}

const ipValidator = (rule: any, value: string, callback: any) => {
    if (value === '') callback()
    const ipv4 = /^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$/;
    const ipv6 = /^([\da-fA-F]{1,4}:){6}((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$|^::([\da-fA-F]{1,4}:){0,4}((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$|^([\da-fA-F]{1,4}:):([\da-fA-F]{1,4}:){0,3}((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$|^([\da-fA-F]{1,4}:){2}:([\da-fA-F]{1,4}:){0,2}((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$|^([\da-fA-F]{1,4}:){3}:([\da-fA-F]{1,4}:)?((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$|^([\da-fA-F]{1,4}:){4}:((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$|^([\da-fA-F]{1,4}:){7}[\da-fA-F]{1,4}$|^:((:[\da-fA-F]{1,4}){1,6}|:)$|^[\da-fA-F]{1,4}:((:[\da-fA-F]{1,4}){1,5}|:)$|^([\da-fA-F]{1,4}:){2}((:[\da-fA-F]{1,4}){1,4}|:)$|^([\da-fA-F]{1,4}:){3}((:[\da-fA-F]{1,4}){1,3}|:)$|^([\da-fA-F]{1,4}:){4}((:[\da-fA-F]{1,4}){1,2}|:)$|^([\da-fA-F]{1,4}:){5}:([\da-fA-F]{1,4})?$|^([\da-fA-F]{1,4}:){6}:$/;

    if (!ipv4.test(value) && !ipv6.test(value)) {
      callback(new Error('请输入正确ip'))
    } else {
      callback()
    }
  }
// 端口-非必填
const validatePort = (rule: any, value: number, callback: any) => {
    if (!(/^[0-9]\d*$/.test(value) && value >= 0 && value <= 65535)) {
      callback(new Error('端口不符合范围:0~65535'))
    } else {
      callback()
    }
    callback()
  }
</script>
<style scoped>
/* .avatar-uploader {
  width: 200px;
} */
</style>